<template>
  <view
    class="tn-navbar"
    :style="navbarStyle"
    :class="navbarClass"
  >
    <!-- 背景颜色 -->
    <view class="tn-navbar__bg" :class="navbarBgClass" :style="navbarBgStyle"></view>
    <!-- 内容 -->
    <view
      class="tn-navbar__wrap"
      :style="navbarWrapStyle"
    >
      <!-- 左边返回按钮内容 -->
      <view
        v-if="isBack"
        class="tn-navbar__back"
        :style="navbarBackStyle"
        @tap="handleBackClick"
      >
        <!-- 只有返回按钮 -->
        <view
          v-if="backType === 'back'"
          class="back"
        >
          <tn-icon v-if="backIcon" :icon="backIcon" :top="1" size="xl"></tn-icon>
          <view
            v-if="backTitle"
            class="back__title tn-text-ellipsis-1"
          >
            {{ backTitle }}
          </view>
        </view>
        <!-- 只有跳转到home -->
        <view
          v-if="backType === 'home'"
          class="home"
          @tap.stop="handleHomeClick"
        >
          <tn-icon :icon="backHomeIcon" :top="-2" color="#FFFFFF" size="lg"></tn-icon>
        </view>
        <!-- 带返回和home的按钮 -->
        <view
          v-if="backType === 'backHome'"
          class="back-home"
        >
          <view class="back-home__back">
            <tn-icon :icon="backIcon" color="#FFFFFF" size="xl"></tn-icon>
          </view>
          <view class="back-home__home" @tap.stop="handleHomeClick">
            <tn-icon :icon="backHomeIcon" color="#FFFFFF" size="xl"></tn-icon>
          </view>
        </view>
        <!-- 自定义返回内容 -->
        <view
          v-if="backType === 'custom'"
          class="custom"
        >
          <slot name="back"></slot>
        </view>
      </view>
      <!-- 中间内容部分 -->
      <view
        class="tn-navbar__content"
        :class="{
          'tn-navbar__content--center': alignCenter
        }"
        :style="navbarContentStyle"
      >
        <slot></slot>
      </view>
    </view>
  </view>
  <!-- 占位内容 -->
  <view
    v-if="fixed"
    class="tn-navbar__placeholder"
    :style="navbarPlaceholderStyle"
  ></view>
</template>

<script lang="ts" setup>
import { navbarProps } from '../../../types/tn-navbar'
import useSystemNavbarInfo from '../lib/useSystemNavbarInfo'
import { computed, CSSProperties, watch } from 'vue'
import { ColorInfo } from '../../../types/tuniao-ui'
import useComponentColor from '../../../libs/hooks/useComponentColor'
import { handleValueWithUnit, navBack, navHome } from '../../../utils'
import TnIcon from '../../tn-icon/src/Icon.vue'

const props = defineProps(navbarProps)

const { splitColorInfo } = useComponentColor()
// 解析背景颜色
const bgColor = computed<ColorInfo>(() => {
  return splitColorInfo('bg', props?.bgColor || '')
})
// 解析字体颜色
const fontColor = computed<ColorInfo>(() => {
  return splitColorInfo('color', props?.color || '')
})

// 导航信息获取
const { 
  navbarHeight, statusHeight, 
  capsuleButtonWidth, capsulrButtonTopDiff, 
  getCustomNavbarHeight, getCapsuleInfo,
  updateNavbarHeight
} = useSystemNavbarInfo()
// 获取自定义导航的高度
getCustomNavbarHeight()
// 获取胶囊信息
getCapsuleInfo()

watch(() => props.height, (val: string | number) => {
  updateNavbarHeight(val)
}, {
  immediate: true
})

// 返回内容类型
type BackContentType = 'custom' | 'back' | 'home' | 'backHome'
const backType = computed<BackContentType>(() => {
  // 使用内置的返回类型
  if (props.backIcon !== '' && props.backHomeIcon !== '') {
    return "backHome"
  } else if (props.backIcon !== '' || props.backTitle !== '') {
    return "back"
  } else if (props.backHomeIcon !== '') {
    return "home"
  }
  return "custom"
})

// 导航栏样式
const navbarStyle = computed<CSSProperties>(() => {
  let style: CSSProperties = {
    opacity: Number(props.opacity) / 100
  }
  const heightValue = handleValueWithUnit(navbarHeight.value, 'px')
  const statusHeightValue = handleValueWithUnit(statusHeight.value, 'px')
  if (heightValue) {
    style.height = heightValue
  }
  if (!props.height && statusHeightValue) {
    style.paddingTop = statusHeightValue
  }
  if (fontColor.value.type === 'style') {
    style.color = fontColor.value.value
  }
  if (props?.zIndex !== 'undefined') {
    style.zIndex = Number(props.zIndex)
  }

  return style
})
// 导航栏内容样式
const navbarWrapStyle = computed<CSSProperties>(() => {
  let style: CSSProperties = {}
  if (!!props?.height) {
    style.height = '100%'
  } else {
    style.height = handleValueWithUnit(Number(navbarHeight.value) - statusHeight.value, 'px')
  }
  return style
})
// 导航栏背景颜色样式
const navbarBgStyle = computed<CSSProperties>(() => {
  let style: CSSProperties = {}
  if (props?.frostedGlass) {
    if (props?.frostedGlassColor) {
      style.backgroundColor = props.frostedGlassColor
    }
  } else {
    if (bgColor.value.type === 'style') {
      style.backgroundColor = bgColor.value.value
    }
  }
  
  return style
})
// 导航栏返回区域内容
const navbarBackStyle = computed<CSSProperties>(() => {
  let style: CSSProperties = {}
  if (!!capsuleButtonWidth.value) {
    // 加多10px补偿外边距
    style.width = handleValueWithUnit(capsuleButtonWidth.value + 10, 'px')
    style.height = `calc(100% - ${2 * capsulrButtonTopDiff.value}px)`
  }
  
  return style
})
// 导航栏中间内容区域样式
const navbarContentStyle = computed<CSSProperties>(() => {
  let style: CSSProperties = {}
  let placeholderWidth: number | string = 0
  // 判断内容区域是否永远居中显示
  if (props.alignCenter) {
    placeholderWidth = capsuleButtonWidth.value * 2
    if (capsuleButtonWidth.value === 0 && props.isBack) {
      placeholderWidth = '25%'
    }
    if (!props?.isBack && !props?.reserveCapsule) {
      placeholderWidth = 0
    }
  } else {
    if (capsuleButtonWidth.value === 0) {
      if (props.isBack) {
        style.left = '25%'
        placeholderWidth = '25%'
      }
    } else {
      // 如果有返回区域则减去对应宽度
      if(props.isBack) {
        style.left = handleValueWithUnit(capsuleButtonWidth.value, 'px')
        placeholderWidth += capsuleButtonWidth.value
      }
      // 如果保留胶囊的信息则减去对应的宽度
      if (props.reserveCapsule) {
        style.right = handleValueWithUnit(capsuleButtonWidth.value, 'px')
        placeholderWidth += capsuleButtonWidth.value
      }
    }
    
  }
  style.width = `calc(100% - ${handleValueWithUnit(placeholderWidth,'px',false)})`
  return style
})
// 导航栏占位内容样式
const navbarPlaceholderStyle = computed<CSSProperties>(() => {
  let style: CSSProperties = {}
  if(props.fixed) {
    const heightValue = handleValueWithUnit(navbarHeight.value, 'px')
    if (heightValue) {
      style.height = heightValue
    }
  }
  return style
})

// 导航栏类
const navbarClass = computed<string>(() => {
  let clazz: string[] = []
  if (fontColor.value.type === 'class') {
    clazz.push(fontColor.value.value)
  }
  if (props.bottomShadow && props.opacity != 0) {
    clazz.push('tn-navbar__bottom-shadow')
  }
  if (!!props.fixed) {
    clazz.push('tn-navbar--fixed')
  }

  return clazz.join(' ')
})
// 导航栏背景颜色
const navbarBgClass = computed<string>(() => {
  let clazz: string[] = []
  if (!props?.frostedGlass && bgColor.value.type === 'class') {
    clazz.push(bgColor.value.value)
  }
  if (props?.frostedGlass) {
    clazz.push('frosted-glass')
  }
  return clazz.join(' ')
})

// 处理点击返回上一页事件
const handleBackClick = async () => {
  if (props.beforeBack && typeof(props.beforeBack) === 'function') {
    let beforeBack = props.beforeBack()
    
    if (beforeBack.then && typeof(beforeBack.then) === 'function') {
      // 判断是否返回Promise
      await beforeBack.then(() => {
        navBack(props.indexUrl)
      }).catch(() => {})
    } else if (beforeBack === true) {
      // 判断是否为普通函数
      navBack(props.indexUrl)
    }
  } else {
    navBack(props.indexUrl)
  }
}
// 处理点击返回首页事件
const handleHomeClick = async () => {
  if (props.beforeHome && typeof(props.beforeHome) === 'function') {
    let beforeHome = props.beforeHome()
    
    if (beforeHome.then && typeof(beforeHome.then) === 'function') {
      // 判断是否返回Promise
      await beforeHome.then(() => {
        navHome(props.indexUrl)
      }).catch(() => {})
    } else if (beforeHome === true) {
      // 判断是否为普通函数
      navHome(props.indexUrl)
    }
  } else {
    navHome(props.indexUrl)
  }
}
</script>

<script lang="ts">
export default {
  options: {
    // 在微信小程序中将组件节点渲染为虚拟节点，更加接近Vue组件的表现(不会出现shadow节点下再去创建元素)
    virtualHost: true
  }
}
</script>

<style lang="scss" scoped>
@import '../../../theme.scss';
.tn-navbar {
  position: relative;
  width: 100%;
  color: $tn-font-color;

  &__bottom-shadow {
    box-shadow: 8rpx 4rpx 6rpx -4rpx #EBEDEB;
  }
  &--fixed {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
  }
  &__wrap {
    position: relative;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: flex-start;
  }
  &__bg {
    width: 100%;
    height: 100%;
    position: absolute;
    left: 0;
    top: 0;
    background-color: #FFFFFF;
    &.frosted-glass {
      background-color: rgba(255, 255, 255, 0.5);
      backdrop-filter: blur(20rpx);
      -webkit-backdrop-filter: blur(20rpx);
    }
  }
  &__back {
    position: relative;
    width: 25%;
    height: 100%;
    display: flex;
    align-items: center;
    overflow: hidden;
    z-index: 1;
    /* #ifdef H5 */
    padding: 10rpx 0rpx;
    /* #endif */
    padding-left: 20rpx;
    .back {
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: flex-start;
      line-height: 1;

      &__title {
        width: 100%;
        margin-left: 6rpx;
      }
    }
    .home {
      background-color: #9C9C9CAA;
      border-radius: 50%;
      width: 52rpx;
      height: 52rpx;
      overflow: hidden;
      padding: 6rpx;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .back-home {
      position: relative;
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;
      background-color: #9C9C9CAA;
      border-radius: 40rpx;
      // padding: 10rpx 0rpx;
      border: 1rpx solid #FFFFFF;
      &__back, &__home {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 100%;
        flex: 1;
      }
      // &__back {
      //   margin-left: 20rpx;
      // }
      // &__home {
      //   margin-right: 20rpx;
      // }
      &::before {
        content: '';
        position: absolute;
        width: 2rpx;
        height: 60%;
        background-color: #FFFFFF;
        left: 50%;
        transform: translateX(-50%);
      }
    }
    .custom {
      width: 100%;
      height: 100%;
    }
  }

  &__content {
    height: 100%;
    position: absolute;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0rpx 20rpx;

    &--center {
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
    }
  }
}
</style>
